package com.evaluation.controller;

import cn.hutool.core.util.StrUtil;
import com.evaluation.common.Result;
import com.evaluation.entity.Weixin;
import com.evaluation.service.WeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * H5认证控制器
 */
@RestController
@RequestMapping("/api/h5/auth")
public class H5AuthController {

    @Autowired
    private WeixinService weixinService;

    /**
     * 验证企业微信用户权限
     */
    @PostMapping("/check")
    public Result<Weixin> checkAuth(@RequestBody Map<String, String> params, HttpSession session) {
        String qywx = params.get("qywx");

        if (StrUtil.isBlank(qywx)) {
            return Result.error("企业微信账号不能为空");
        }

        try {
            // 根据企业微信账号查询用户信息
            Weixin weixin = weixinService.getByQywx(qywx);

            if (weixin == null || StrUtil.isBlank(weixin.getJsxm())) {
                return Result.error("您无访问权限，请联系管理员");
            }

            // 将用户信息保存到session中
            session.setAttribute("currentUser", weixin);
            session.setAttribute("currentUserName", weixin.getJsxm());
            session.setMaxInactiveInterval(3600 * 24); // 24小时超时

            return Result.success(weixin);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统错误，请稍后重试");
        }
    }

    /**
     * 用户退出登录
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpSession session) {
        try {
            session.invalidate();
            return Result.success("退出成功");
        } catch (Exception e) {
            // Session可能已经无效，直接返回成功
            return Result.success("退出成功");
        }
    }
}
